<template>
  <div class="bridge-evaluation-container">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true" style="display: flex;justify-content: space-between;width: 100%;">
            <div style="display: flex;align-items: center;">
              <el-form-item label="评估总结" prop="comments">
                <el-input v-model="queryParams.comments" placeholder="请输入评估总结" clearable @keyup.enter="handleQuery" />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              </el-form-item>
            </div>
            <div style="display: flex;align-items: center;">
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
              <el-button type="primary" @click="handleAdd" class="custom-button">
                <el-icon>
                  <Plus />
                </el-icon>
                新增评估
              </el-button>
              <el-button type="primary" @click="goToEvaluationRules" class="custom-button">
                <el-icon>
                  <Document />
                </el-icon>
                评分规则
              </el-button>
            </div>
          </el-form>
        </el-card>
      </div>
    </transition>

    <!-- 数据表格 -->
    <el-table v-loading="loading" :data="tableData" @selection-change="handleSelectionChange" class="custom-table">
      <el-table-column type="selection" width="55" />
      <el-table-column prop="eventId" label="事件描述" min-width="180">
        <template #default="{ row }">
          {{ row.eventDescription || getEventDescription(row.eventId) }}
        </template>
      </el-table-column>
      <el-table-column prop="deptId" label="评估部门" width="120" />
      <el-table-column prop="evaluationTime" label="评估时间" width="180">
        <template #default="{ row }">
          {{ formatDateTime(row.evaluationTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="totalScore" label="最终评分" width="100" align="center">
        <template #default="{ row }">
          <span :class="getScoreClass(row.totalScore)">{{ row.totalScore || '0' }}分</span>
        </template>
      </el-table-column>
      <el-table-column prop="comments" label="评估总结" min-width="200" show-overflow-tooltip />
      <el-table-column label="操作" width="180" fixed="right" align="center">
        <template #default="{ row }">
          <el-button link type="primary" @click="handleView(row)" class="operation-button"> 查看</el-button>
          <el-button link type="primary" @click="handleEdit(row)" class="operation-button"> 编辑</el-button>
          <el-button link @click="handleDelete(row)" class="operation-button danger"> 删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页器 -->
    <div class="pagination-container">
      <el-pagination
        background
        :current-page="currentPage"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑弹窗 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="60%" class="custom-dialog">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px" class="dialog-form">
        <el-form-item label="选择事件" prop="eventId">
          <el-select v-model="form.eventId" placeholder="请选择事件" class="w-full" filterable>
            <el-option v-for="item in eventOptions" :key="item.id" :label="item.description" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="评估部门" prop="deptId">
          <el-input v-model="form.deptId" placeholder="请输入评估部门ID" />
        </el-form-item>
        <el-form-item label="评估时间" prop="evaluationTime">
          <el-date-picker
            v-model="form.evaluationTime"
            type="datetime"
            placeholder="选择评估时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            :default-time="new Date(2000, 1, 1, 0, 0, 0)"
            class="w-full"
          />
        </el-form-item>

        <!-- 评分表格 -->
        <div class="score-table-title">评分项目</div>
        <el-table :data="scoreItems" border class="score-table">
          <el-table-column prop="content" label="评分维度" min-width="150" />
          <el-table-column prop="maxScore" label="最高分值" width="100" align="center" />
          <el-table-column prop="weight" label="权重" width="100" align="center">
            <template #default="{ row }"> {{ (row.weight * 100).toFixed(0) }}%</template>
          </el-table-column>
          <el-table-column label="得分" width="150" align="center">
            <template #default="{ row }">
              <el-input-number
                v-model="row.score"
                :min="0"
                :max="row.maxScore"
                :precision="1"
                controls-position="right"
                @change="calculateTotalScore"
              />
            </template>
          </el-table-column>
        </el-table>

        <div class="total-score-display">
          <span class="label">最终评分：</span>
          <span class="value" :class="getScoreClass(form.totalScore)">{{ form.totalScore || '0' }}分</span>
        </div>

        <el-form-item label="评估总结" prop="comments">
          <el-input type="textarea" v-model="form.comments" :rows="4" placeholder="请输入评估总结和补充说明" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
      </template>
    </el-dialog>

    <!-- 查看详情弹窗 -->
    <el-dialog title="评估详情" v-model="viewDialogVisible" width="60%" class="custom-dialog">
      <div class="detail-view" v-if="detailData">
        <div class="detail-item">
          <span class="label">事件描述：</span>
          <span class="value">{{ detailData.eventDescription || getEventDescription(detailData.eventId) }}</span>
        </div>
        <div class="detail-item">
          <span class="label">评估部门：</span>
          <span class="value">{{ detailData.deptId }}</span>
        </div>
        <div class="detail-item">
          <span class="label">评估时间：</span>
          <span class="value">{{ formatDateTime(detailData.evaluationTime) }}</span>
        </div>
        <div class="detail-item">
          <span class="label">最终评分：</span>
          <span class="value" :class="getScoreClass(detailData.totalScore)">{{ detailData.totalScore || '0' }}分</span>
        </div>

        <!-- 评分详情表格 -->
        <div class="score-detail-title">评分详情</div>
        <el-table :data="detailScoreItems" border class="score-table">
          <el-table-column prop="content" label="评分维度" min-width="150" />
          <el-table-column prop="maxScore" label="最高分值" width="100" align="center" />
          <el-table-column prop="weight" label="权重" width="100" align="center">
            <template #default="{ row }"> {{ (row.weight * 100).toFixed(0) }}%</template>
          </el-table-column>
          <el-table-column prop="score" label="得分" width="100" align="center" />
          <el-table-column label="得分率" width="100" align="center">
            <template #default="{ row }"> {{ ((row.score / row.maxScore) * 100).toFixed(1) }}%</template>
          </el-table-column>
        </el-table>

        <div class="detail-item detail-comments">
          <div class="label">评估总结：</div>
          <div class="value comments-text">{{ detailData.comments || '无' }}</div>
        </div>
      </div>
      <template #footer>
        <el-button @click="viewDialogVisible = false">关 闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, getCurrentInstance, type ComponentInternalInstance } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import {
  getDisposalEvaluationList,
  getDisposalEvaluationDetail,
  addDisposalEvaluation,
  updateDisposalEvaluation,
  deleteDisposalEvaluation
} from '@/api/bridge/command/evaluation';
import { getEmergencyEventList } from '@/api/bridge/command/event';
import { getEvaluationRuleList } from '@/api/bridge/command/evaluation';
import dayjs from 'dayjs';
import { Plus, RefreshRight, Document } from '@element-plus/icons-vue';
import { useRouter } from 'vue-router';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const router = useRouter();

// 表格数据
const tableData = ref([]);
const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const selectedRows = ref([]);
const showSearch = ref(true);

// 事件选项
const eventOptions = ref([]);

// 评分项数据
const scoreItems = ref([]);

// 查看详情相关
const viewDialogVisible = ref(false);
const detailData = ref(null);
const detailScoreItems = ref([]);

// 弹窗相关
const dialogVisible = ref(false);
const dialogTitle = ref('');
const formRef = ref();
const form = ref({
  id: '',
  eventId: '',
  deptId: '',
  evaluationTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
  totalScore: 0,
  comments: '',
  scoreItems: [] // 存储各项评分
});

// 表单校验规则
const rules = {
  eventId: [{ required: true, message: '请选择事件', trigger: 'change' }],
  deptId: [{ required: true, message: '请输入评估部门', trigger: 'blur' }],
  evaluationTime: [{ required: true, message: '请选择评估时间', trigger: 'change' }],
  comments: [{ required: true, message: '请输入评估总结', trigger: 'blur' }]
};

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  type: null,
  comments: null
});

const queryFormRef = ref<any>(null);

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNum = 1;
  getList();
};

const resetQuery = () => {
  // 在这里添加重置逻辑
  queryParams.comments = null;
  queryFormRef.value?.resetFields();
  // 调用查询接口
  getList();
};

// 格式化日期时间
const formatDateTime = (date) => {
  if (!date) return '-';
  return dayjs(date).format('YYYY-MM-DD HH:mm:ss');
};

// 获取评分样式
const getScoreClass = (score) => {
  if (!score) return 'score-low';
  score = parseFloat(score);
  if (score >= 80) return 'score-high';
  if (score >= 60) return 'score-medium';
  return 'score-low';
};

// 获取事件描述
const getEventDescription = (eventId) => {
  if (!eventId) return '-';
  const event = eventOptions.value.find((item) => item.id === eventId);
  return event ? event.description : `事件ID: ${eventId}`;
};

// 获取列表数据
const getList = async () => {
  loading.value = true;
  try {
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      comments: queryParams.comments
    };
    const res = await getDisposalEvaluationList(params);
    if (res.code === 200) {
      tableData.value = res.rows;
      total.value = res.total;
    }
  } catch (error) {
    console.error('获取数据失败:', error);
  } finally {
    loading.value = false;
  }
};

// 获取事件列表
const getEventList = async () => {
  try {
    const res = await getEmergencyEventList({
      pageNum: 1,
      pageSize: 1000
    });
    if (res.code === 200) {
      eventOptions.value = res.rows;
    }
  } catch (error) {
    console.error('获取事件列表失败:', error);
  }
};

// 获取评分规则列表
const getScoreRules = async () => {
  try {
    const res = await getEvaluationRuleList({
      pageNum: 1,
      pageSize: 1000,
      status: 1 // 只获取启用状态的规则
    });
    if (res.code === 200) {
      return res.rows;
    }
    return [];
  } catch (error) {
    console.error('获取评分规则失败:', error);
    return [];
  }
};

// 初始化评分项
const initScoreItems = async () => {
  const rules = await getScoreRules();
  scoreItems.value = rules.map((rule) => ({
    ruleId: rule.id,
    content: rule.content,
    maxScore: rule.maxScore,
    weight: rule.weight,
    score: 0
  }));
};

// 计算总分
const calculateTotalScore = () => {
  if (scoreItems.value.length === 0) return 0;

  let totalScore = 0;
  for (const item of scoreItems.value) {
    totalScore += item.score * item.weight;
  }

  form.value.totalScore = parseFloat(totalScore.toFixed(2));
};

// 处理新增
const handleAdd = () => {
  dialogTitle.value = '新增处置效果评估';
  form.value = {
    id: '',
    eventId: '',
    deptId: '',
    evaluationTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
    totalScore: 0,
    comments: '',
    scoreItems: []
  };
  initScoreItems();
  dialogVisible.value = true;
};

// 处理编辑
const handleEdit = async (row) => {
  try {
    const res = await getDisposalEvaluationDetail(row.id);
    if (res.code === 200) {
      form.value = {
        ...res.data,
        evaluationTime: res.data.evaluationTime
          ? dayjs(res.data.evaluationTime).format('YYYY-MM-DD HH:mm:ss')
          : dayjs().format('YYYY-MM-DD HH:mm:ss'),
        scoreItems: res.data.scoreItems || []
      };

      // 初始化评分项
      await initScoreItems();

      // 如果有历史评分数据，填充到表格中
      if (res.data.scoreItems && res.data.scoreItems.length > 0) {
        res.data.scoreItems.forEach((item) => {
          const index = scoreItems.value.findIndex((i) => i.ruleId === item.ruleId);
          if (index !== -1) {
            scoreItems.value[index].score = item.score;
          }
        });
      }

      dialogTitle.value = '编辑处置效果评估';
      dialogVisible.value = true;
    }
  } catch (error) {
    ElMessage.error('获取详情失败');
  }
};

// 处理查看
const handleView = async (row) => {
  try {
    const res = await getDisposalEvaluationDetail(row.id);
    if (res.code === 200) {
      detailData.value = res.data;

      // 获取评分项详情
      const rules = await getScoreRules();

      if (res.data.scoreItems && res.data.scoreItems.length > 0) {
        detailScoreItems.value = res.data.scoreItems.map((item) => {
          const rule = rules.find((r) => r.id === item.ruleId);
          return {
            ...item,
            content: rule ? rule.content : item.content || '未知维度',
            maxScore: rule ? rule.maxScore : item.maxScore || 0,
            weight: rule ? rule.weight : item.weight || 0
          };
        });
      } else {
        detailScoreItems.value = [];
      }

      viewDialogVisible.value = true;
    }
  } catch (error) {
    ElMessage.error('获取详情失败');
  }
};

// 处理删除
const handleDelete = (row) => {
  ElMessageBox.confirm('确认删除该评估记录吗？', '提示', {
    type: 'warning'
  }).then(async () => {
    try {
      const res = await deleteDisposalEvaluation(row.id);
      if (res.code === 200) {
        ElMessage.success('删除成功');
        await getList();
      } else {
        ElMessage.error(res.msg || '删除失败');
      }
    } catch (error) {
      ElMessage.error('删除失败');
    }
  });
};

// 表格选择改变
const handleSelectionChange = (rows) => {
  selectedRows.value = rows;
};

// 处理表单提交
const handleSubmit = async () => {
  if (!formRef.value) return;
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 组装提交数据
        const submitData = {
          ...form.value,
          scoreItems: scoreItems.value.map((item) => ({
            ruleId: item.ruleId,
            score: item.score
          }))
        };

        if (form.value.id) {
          const res = await updateDisposalEvaluation(submitData);
          if (res.code === 200) {
            ElMessage.success('修改成功');
            dialogVisible.value = false;
            await getList();
          } else {
            ElMessage.error(res.msg || '修改失败');
          }
        } else {
          const res = await addDisposalEvaluation(submitData);
          if (res.code === 200) {
            ElMessage.success('新增成功');
            dialogVisible.value = false;
            await getList();
          } else {
            ElMessage.error(res.msg || '新增失败');
          }
        }
      } catch (error) {
        ElMessage.error('操作失败');
      }
    }
  });
};

// 分页相关方法
const handleSizeChange = (val) => {
  pageSize.value = val;
  getList();
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  getList();
};

const goToEvaluationRules = () => {
  router.push('/coordination-command/evaluation-rules');
};

onMounted(() => {
  getList();
  getEventList();
});
</script>

<style scoped lang="scss">
.bridge-evaluation-container {
  padding: 20px;
  height: 100%;
  background: var(--el-bg-color-page);
  border-radius: 4px;
  box-shadow: var(--el-box-shadow-light);

  .operation-bar {
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;
    background: var(--el-bg-color-overlay);
    padding: 16px;
    border-radius: 4px;

    .left {
      .page-title {
        margin: 0;
        font-size: 18px;
        font-weight: 600;
        color: var(--el-text-color-primary);
      }
    }

    .right {
      display: flex;
      gap: 12px;
    }

    .custom-button {
      transition: all 0.3s;

      &:hover {
        transform: translateY(-2px);
      }
    }

    .refresh-button {
      transition: all 0.3s ease;

      &:hover {
        transform: rotate(180deg);
      }
    }
  }

  .custom-table {
    margin-bottom: 20px;
    border-radius: 8px;
    overflow: hidden;
    background: var(--el-bg-color-overlay);

    :deep(th) {
      background: var(--el-bg-color-page) !important;
    }

    :deep(.el-table__row) {
      background-color: var(--el-bg-color-overlay);
    }

    .operation-button {
      padding: 2px 8px;
      margin: 0 2px;
      font-size: 12px;

      &.danger {
        color: var(--el-color-danger);
      }

      &:hover {
        opacity: 0.8;
      }
    }
  }

  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}

.custom-dialog {
  :deep(.el-dialog) {
    border-radius: 12px;
    background: var(--el-bg-color-overlay);

    .el-dialog__header {
      background: var(--el-bg-color-page);
      margin: 0;
      padding: 20px;
      border-bottom: 1px solid var(--el-border-color-light);
    }

    .el-dialog__body {
      padding: 30px 20px;
    }

    .el-dialog__footer {
      border-top: 1px solid var(--el-border-color-light);
      padding: 15px 20px;
    }
  }

  .dialog-form {
    :deep(.el-form-item__label) {
      color: var(--el-text-color-regular);
    }

    :deep(.el-input__inner) {
      background-color: var(--el-bg-color-overlay);
      border-color: var(--el-border-color);
      color: var(--el-text-color-primary);
    }
  }
}

.w-full {
  width: 100%;
}

/* 评分相关样式 */
.score-table-title,
.score-detail-title {
  font-size: 16px;
  font-weight: 600;
  margin: 20px 0 10px;
  color: var(--el-text-color-primary);
  display: flex;
  align-items: center;

  &::before {
    content: '';
    display: inline-block;
    width: 4px;
    height: 16px;
    background-color: var(--el-color-primary);
    margin-right: 8px;
    border-radius: 2px;
  }
}

.score-table {
  margin-bottom: 20px;

  :deep(.el-input-number) {
    width: 120px;
  }
}

.total-score-display {
  margin: 20px 0;
  padding: 15px;
  background-color: var(--el-fill-color-light);
  border-radius: 4px;
  display: flex;
  align-items: center;

  .label {
    font-size: 16px;
    font-weight: 600;
    margin-right: 10px;
  }

  .value {
    font-size: 24px;
    font-weight: 700;
  }
}

/* 评分颜色 */
.score-high {
  color: var(--el-color-success);
}

.score-medium {
  color: var(--el-color-warning);
}

.score-low {
  color: var(--el-color-danger);
}

/* 详情查看样式 */
.detail-view {
  .detail-item {
    margin-bottom: 15px;
    display: flex;

    .label {
      width: 120px;
      font-weight: 600;
      color: var(--el-text-color-regular);
    }

    .value {
      flex: 1;
      color: var(--el-text-color-primary);
    }

    &.detail-comments {
      display: block;

      .label {
        display: block;
        margin-bottom: 8px;
      }

      .comments-text {
        padding: 15px;
        background-color: var(--el-fill-color-light);
        border-radius: 4px;
        min-height: 80px;
        white-space: pre-line;
      }
    }
  }
}
</style>
